<?php
namespace core;

// require 'common.php';
// 视图类

// 试图->模板->有数据展位符的字符串

// 模板入口: app/admin/view/
class view
{
    // 模板入口路径
    protected string $defaultPath;
    // 当前controller
    protected string $controller;
    // 当前方法
    protected string $action;
    // 模板变量容器
    public array $data = [];
    // 构造器
    public function __construct(string $defaultPath,string $controller,string $action)
    {
        $this->defaultPath = $defaultPath;
        $this->controller = $controller;
        $this->action = $action;
    }
    // 1.模板赋值
    public function assign($key,$value=null)
    {
        if(is_array($key)){
            $this->data = array_merge($this->data, $key);
        } else {
            $this->data[$key] = $value;
        }
    }
    // 2.渲染模板
    public function render(string $path=null, array $data = [])
    {
        //允许模板赋值和模板渲染
        $this->data = $data ? array_merge($this->data, $data) : $this->data;
        // extract将一个关联数组展开
        // ['id'=>1,'uname'=>'admin'] => $id=1,$uname='admin'
        extract($this->data);
        $file = $this->defaultPath.$this->controller.'/'.$this->action.'.php';
        file_exists($file) ? include $file : die('模板文件不存在');
    }
        
}

// $view = new View('../app/admin/view/', 'index', 'index');
// $view->assign('username', '朱老师');
// $view->assign('email', 'ww@qq.com');
// // $view->assign('username',['username'=>'朱老师']);
// $data = ['lesson'=>'php,java', 'score'=>90, 'username'=>'王老师'];
// $view->assign($data);

// d($view->data);
// d($view->render());
?>